package com.zcsy.seller.web.store;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.sms.dlife.DlifeSmsConfig;
import com.zcsy.commons.util.MD5Util;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IVerifyCodeService;
import com.zcsy.manage.service.sms.DlifeSmsService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.seller.web.common.SixCodeUtil;

/**
 * @Project: seller
 * @Title: PersonalInfoController
 * @Package com.zcsy.seller.web.personal
 * @Description:个人信息控制层
 * @author fangli Fanglwj520@163.com
 * @date 2016年5月26日 下午5:31:19
 * @Copyright：2014 武汉恒数利通软件有限公司 All rights reserved.
 * @version 1.0
 */
@Controller
@RequestMapping(value="/personalInfo")
public class PersonalInfoController {
	
    @Autowired
    private IUserService userService;
    
    @Autowired
    private DlifeSmsService dlifesmsService;
    
    @Autowired
    private IVerifyCodeService verifyCodeService;
    
    private static final int USER_CHECK = 1;
    
    private static final int PHONE_BIND = 2;
    

    /**
     * @Description:个人信息展示
     * @param id 用户id
     * @param req
     * @return: 跳转页面url
     * @author: fangli
     * @Date: 2016年5月26日
     */
    @RequestMapping(value = "personalInfoList", method = RequestMethod.GET)
    public String getUserListBySearchKey(Model model, HttpServletRequest req) {
        
         User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID); 
       //将电话号码中间四位隐藏起来
       //  String phone = user.getPhone();
        // phone = phone.substring(0,3) + "****" + phone.substring(7, phone.length());
        // user.setPhone(phone);
         
         User userList = userService.selectByPrimaryKey(user.getId());
         model.addAttribute("userInfo", userList);
         model.addAttribute("sex", userList.getSex());

        return "store/personalinfo/personalInfoList";
    } 
    
    /**
     * @Description 更新个人信息<br>
     * @param lname 账号
     * @param phone 电话
     * @param nickname 昵称
     * @param uname 姓名
     * @param userId 用户id
     * @param email 邮箱
     * @param loginTimes 登陆次数
     * @param request 用户请求
     * @param response 响应
     * @return 
     * @author fangli
     * @date 2016年5月30日
     * @see 
     */
    @RequestMapping(value = "UpdatePersonalInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson UpdatePersonalInfo(String loginname,String phone,
    		String nickname,String username,Integer sex,String email,Date lastLoginTime,
    		Integer loginTimes,String imageLogo, HttpServletRequest request,HttpServletResponse response) {
        RequestJson result = new RequestJson();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            User record = userService.selectByPrimaryKey(user.getId());
            
            record.setLoginname(loginname);
            record.setPhone(phone);
            record.setNickname(nickname);
            record.setUsername(username);
            record.setSex(sex);
            record.setEmail(email);
            record.setLoginTimes(loginTimes);
            record.setLastLoginTime(lastLoginTime);
            record.setLogo(imageLogo);
            record.setId(user.getId());
            userService.updateByPrimaryKeySelective(record);
     
        }catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    } 
    
    /**
     * @Description 修改用户密码
     * @param id 用户id
     * @return 跳转页面url
     * @author fangli
     * @date 2016年5月27日
     * @see 
     */
    @RequestMapping(value = "changePassword", method = RequestMethod.GET)
    public String changePassword(Model model, HttpServletRequest req) {
        try {
            User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "store/changepwd/changePassword";
    }
  
    /**
     * @Description 保存密码
     * @param id 主键id
     * @param uname 用户名
     * @param oldPwd 当前密码
     * @param newPwd 新密码
     * @param req 用户请求
     * @return 响应结果
     * @author fangli
     * @date 2016年5月27日
     * @see 
     */
    @RequestMapping(value = "savePassword", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson savePassword(String id, String loginName,
    		                        String oldPwd, String newPwd, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            //校验的用户对象
            final User user = userService.selectByPrimaryKey(id);
            
            //更新密码的用户对象
            User userVo = new User();
            
            //生成密匙
//            final String oldUserKey = MD5Util.generalPassword(loginName,oldPwd);
//            final String newUserKey = MD5Util.generalPassword(loginName,newPwd);
            
            //密码校验
            if(oldPwd.equals(user.getPwd())){
                userVo.setId(id);
                userVo.setPwd(newPwd);
                userService.updateByPrimaryKeySelective(userVo);
                
                result.setSuccess(true);
                result.setMsg("操作成功");
                
            }else{
                result.setMsg("密码错误");
                result.setSuccess(false);
                
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        
        return result;
    }
    
    /**
     * 
     * @Description 返回商户身份验证页面
     * 
     * @param model
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月13日
     * @see
     */
    @RequestMapping(value = "userCheck", method = RequestMethod.GET)
    public String userCheck(Model model, HttpServletRequest req) {
        try {
            User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            	model.addAttribute("user", user);
            	String phone = user.getPhone();
            	if(StringUtils.isNotEmpty(phone)){
            	model.addAttribute("type", USER_CHECK);
            	} else {
            		model.addAttribute("type", PHONE_BIND);	
            	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
        
        return "store/bindphone/bindPhone";
        
    }
    
    /**
     * 
     * @Description 返回绑定手机页面
     * 
     * @param model
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月13日
     * @see
     */
    @RequestMapping(value = "bindPhone", method = RequestMethod.GET)
    public String bindPhone(Model model, HttpServletRequest req) {
    	model.addAttribute("type", PHONE_BIND);
    	model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
    	
    	return "store/bindphone/bindPhone";
        
    }
    
    /**
     * 
     * @Description 返回手机绑定完成页面
     * 
     * @param model
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月13日
     * @see
     */
    @RequestMapping(value = "bindComplete", method = RequestMethod.GET)
    public String bindComplete(Model model, HttpServletRequest req) {
    	model.addAttribute("type", PHONE_BIND);
    	
    	return "store/bindphone/bindComplete";
    }
    
    /**
     * 
     * @Description 绑定手机发送验证码信息
     * 
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月12日
     * @see
     */
    @RequestMapping(value = "sendOldPhone", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sendMSG(HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try{
    		 User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    		 String phone = user.getPhone();
    		 //随机生成六位数验证码
    		 String phoneCode = SixCodeUtil.sixCode();
    		 user.setUserType(Constants.OWNER_TYPE);
    		 verifyCodeService.sendCodeMessage(user, phone, phoneCode, result);
    		 
    	}  catch (Exception e) {
             result.setSuccess(false);
             result.setMsg("操作失败");
             e.printStackTrace();
        }
    	
		return result;
    	
    }
    
    /**
     * 
     * @Description 绑定新手机号发送验证码
     * 
     * @param phone 新手机号
     * @param id 主键id
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月14日
     * @see
     */
    @RequestMapping(value = "sendNewPhone", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson savaPhone(String phone, String id, HttpServletRequest req) {
    	RequestJson result = new RequestJson();
    	try{
    		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    		user.setPhone(phone);
    		user.setId(id);
    		userService.updateByPrimaryKeySelective(user);
    		//随机生成六位数验证码
    		String phoneCode = SixCodeUtil.sixCode();
    		user.setUserType(Constants.BUSINESS_TYPE);
    		verifyCodeService.sendCodeMessage(user, phone, phoneCode, result);
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    		result.setSuccess(false);
    		result.setMsg("操作失败");
    	}
    	
    	return result;
    }
    
    /**
     * 
     * @Description 判断输入的登录名是否存在<br>
     * 
     * @param loginName 登录名
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月21日
     * @see
     */
    @RequestMapping(value="isUser" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson isUser(String loginName,HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
            //验证登录名和手机号
            User loginUser = new User();
            loginUser.setPhone(loginName);
            loginUser.setUserType(Constants.BUSINESS_TYPE);
            User user = userService.userLogin(loginUser);
            //取出当前用户在当前小区的roleList角色集合
            if (user == null) {
                
                result.setMsg("用户不存在");
                result.setSuccess(false);
                return result;
            }
            
            if(user.getState().intValue() != 1){
                result.setMsg("用户已停用");
                result.setSuccess(false);
                return result;
            }
        	result.setSuccess(true);
        	result.setMsg("操作成功");
        	
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        
        return result;
     
}
    
    /**
     * 
     * @Description 返回找回密码页面<br>
     * 
     * @param model
     * @param loginName 用户登录名
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月21日
     * @see
     */
    @RequestMapping(value = "findPassword", method = RequestMethod.GET)
    public String findPassword( Model model,String loginName, HttpServletRequest req) {
    	try{
    		if(StringUtils.isNotEmpty(loginName)){
    		    User loginUser = new User();
    		    loginUser.setUserType(Constants.BUSINESS_TYPE);
    		    loginUser.setPhone(loginName);
                User user = userService.userLogin(loginUser);
    			model.addAttribute("user", user);
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
    	
    	return "common/findPassword";
        
    }
    
    /**
     * 
     * @Description 忘记密码发送验证码修改密码<br>
     * 
     * @param name 登录名
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月16日
     * @see
     */
    @RequestMapping(value = "sendCode", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sendCode(String lname, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try{
    		 User user = userService.selectByPhone(lname);
    		 if (user != null){
    			 String phone = user.getPhone();
    			 //随机生成六位数验证码
    			 String phoneCode = SixCodeUtil.sixCode();
    			 
    			 user.setUserType(Constants.BUSINESS_TYPE);
    			verifyCodeService.sendCodeMessage(user, phone, phoneCode, result);
    			 
    		 }
    	}  catch (Exception e) {
             result.setSuccess(false);
             result.setMsg("操作失败");
             e.printStackTrace();
        }
    	
		return result;
    }
    
    /**
     * 
     * @Description 保存新密码<br>
     * 
     * @param loginName 用户登录名
     * @param newPwd 新密码
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月21日
     * @see
     */
    @RequestMapping(value="completePassword" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateAdInfo(String loginName,String newPwd,HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user = userService.selectByPhone(loginName);
        user.setPwd(newPwd);
        try {
            //生成密匙
//            final String newUserKey = MD5Util.generalPassword(loginName,newPwd);
            user.setPwd(newPwd);
            userService.updateByPrimaryKeySelective(user);
            
            result.setSuccess(true);
            result.setMsg("操作成功");
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        
        return result;
     
}
}
